bleh
[mqlkit.git] / james tran.mq4
blob9c2d6fd890b69fd28223a6c1fe5d7a485a50efed
1 //+------------------------------------------------------------------+\r
2 //|                                            James tran_EA.mq4 |\r
3 //|                                       Copyright 2010, james tran. |\r
4 //|                                               |\r
5 //+------------------------------------------------------------------+\r
6 \r
7  \r
8 #property copyright "Copyright 2010, James tran."    \r
9 \r
11 //+------------------------------------------------------------------+\r
12 //| Universal Constants                                              |\r
13 //+------------------------------------------------------------------+\r
14 #define TRADEPEND  -1\r
15 #define TRADEALL   0\r
16 #define TRADETRADE 1\r
17 #define TRADEBUY   1\r
18 #define TRADESELL  -1\r
20 #define CANDLE_BULL 1\r
21 #define CANDLE_BEAR -1\r
22 #define CANDLE_NONE 0\r
24 //+------------------------------------------------------------------+\r
25 //| User input variables                                             |\r
26 //+------------------------------------------------------------------+\r
27 extern string     AdvisorName = "KellyL_Ranging_EA";          // For Logging\r
28 extern string  AdvisorVersion = "1.0.2";            // The version number of this script\r
29 extern string     ProjectPage = "http://kolier.li/project/kellyl-ranging-ea";            // The project landing page\r
30 // Trade Time Filter - @see http://kolier.li/example/script-function-trade-time-filter\r
31 extern string Trade_Time_Filter = "http://kolier.li/example/script-function-trade-time-filter";\r
32 extern bool   TradeTimeFilter = false;          // Whether to use trade time filter\r
33 extern string      TradeBegin = "07:00";       // Don't trade before this time\r
34 extern string        TradeEnd = "19:00";       // Don't trade after this time\r
35 extern bool     EndInTomorrow = false;         // Whether TradeEnd is the next day, like you want to trade the period: 18:00~06:00, the 06:00 is the next am\r
36 // Order Operation - Open: @see http://kolier.li/example/script-function-order-operation-open\r
37 extern string Order_Operation_Open = "http://kolier.li/example/script-function-order-operation-open";\r
38 extern double    ProfitTarget = 10;            // In account currency, usually in dollar.\r
39 extern bool         ECNBroker = false;         // Whether using ECN broker\r
40 extern int              Magic = 222222;        // For identify trades belong to this EA, set to unique on different chart when using at the same time\r
41 extern int           Slippage = 3;             // Allow slippage\r
42 extern double            LotsInit = 0.1;           // Trade lots\r
43 extern bool       StealthMode = false;         // Whether TakeProfit and StopLoss in Stealth Mode, hiding from the broker\r
44 extern double      TakeProfit1 = 100;             // In Pips. Take Profit, Change to 0 if you don't want to use.\r
45 extern double        StopLoss1 = 100;             // In Pips. Stop Loss, Change to 0 if you don't want to use.\r
46 // Secondary Trade                                                      \r
47 extern bool    UseTrade2 = true;\r
48 extern bool    BuySell2 = true;         \r
49 extern double   LastLoss2 = 40;                    // In Pips.\r
50 extern double     TakeProfit2 = 100;                      // In Pips.\r
51 extern double       StopLoss2 = 100;                 // In Pips.\r
52 extern double        LotMult2 = 2.0;            \r
53 // Third Trade                                                  \r
54 extern bool     UseTrade3 = true;       \r
55 extern bool    BuySell3 = true; \r
56 extern double   LastLoss3 = 40;                    // In Pips.\r
57 extern double     TakeProfit3 = 100;\r
58 extern double       StopLoss3 = 100;\r
59 extern double        LotMult3 = 3.0;\r
60 // Forth Trade                                                  \r
61 extern bool     UseTrade4 = true;       \r
62 extern bool    BuySell4 = true; \r
63 extern double   LastLoss4 = 40;                    // In Pips.\r
64 extern double     TakeProfit4 = 100;\r
65 extern double       StopLoss4 = 100;\r
66 extern double        LotMult4 = 4.0;\r
67 // Fifth Trade                                                  \r
68 extern bool     UseTrade5 = true;\r
69 extern bool    BuySell5 = true;         \r
70 extern double   LastLoss5 = 40;                    // In Pips.\r
71 extern double     TakeProfit5 = 100;\r
72 extern double       StopLoss5 = 100;\r
73 extern double        LotMult5 = 5.0;\r
74 // six Trade                                                    \r
75 extern bool     UseTrade6 = true;       \r
76 extern bool    BuySell6 = true; \r
77 extern double   LastLoss6 = 100;                           // In Pips.\r
78 extern double     TakeProfit6 = 100;\r
79 extern double       StopLoss6 = 100;\r
80 extern double        LotMult6 = 6.0;\r
81 // Order Operation - Break Even: @see http://kolier.li/example/script-function-order-operation-breakeven\r
82 extern string Order_Operation_BreakEven = "http://kolier.li/example/script-function-order-operation-breakeven";\r
83 extern bool      UseBreakEven = false;          // Whether using BreakEven\r
84 extern bool    BE_StealthMode = false;         // Whether using BreakEven in Stealth Mode\r
85 extern double   BreakEvenPips = 20;            // In Pips. BreakEven Pips.\r
86 extern bool BreakEvenWithProfit = false;       // Different from normal BreakEven, you can make a little in BreakEven, like 1~2 pips\r
87 extern double BreakEvenProfit = 3;             // In Pips. BreakEven Pips take profit.\r
88 // Order Operation - Trailing Stop: @see http://kolier.li/example/script-function-order-operation-trailing-stop\r
89 extern string Order_Operation_Trailing_Stop = "http://kolier.li/example/script-function-order-operation-trailing-stop";\r
90 extern bool      UseTrailStop = false;          // Whether using TrailStop\r
91 extern bool    TrailAfterEven = true;          // Whether using TrailStop after the range between current price and the OrderOpenPrice >= TrailStopPips\r
92 extern bool    TS_StealthMode = false;         // Whether using TrailStop in Stealth Mode\r
93 extern double   TrailStopPips = 20;            // In Pips. TrailStop Pips\r
94 extern bool  TS_MovingInChunk = false;         // Whether wait for price move a range to set new SL\r
95 extern double        TS_Chunk = 10;            // In Pips. Moving pips as chunk\r
98 //+------------------------------------------------------------------+\r
99 //| Universal variables                                              |\r
100 //+------------------------------------------------------------------+\r
101 int TradeOn_n[6], num_trades=0, BuySell_n[6];\r
102 double Lots_n[6], Lots, TP_n[6], TakeProfit, SL_n[6], StopLoss, LastLoss_n[6];\r
103 datetime time_check;\r
104 int tickets[6]; \r
106 //+------------------------------------------------------------------+\r
107 //| expert initialization function                                   |\r
108 //+------------------------------------------------------------------+\r
109 int init()\r
110   {\r
111    Lots_n[0] = LotsInit;\r
112    Lots_n[1] = LotsInit*LotMult2;\r
113    Lots_n[2] = LotsInit*LotMult3;\r
114    Lots_n[3] = LotsInit*LotMult4;\r
115    Lots_n[4] = LotsInit*LotMult5;\r
116    Lots_n[5] = LotsInit*LotMult6;\r
117    TP_n[0] = TakeProfit1;\r
118    TP_n[1] = TakeProfit2;\r
119    TP_n[2] = TakeProfit3;\r
120    TP_n[3] = TakeProfit4;\r
121    TP_n[4] = TakeProfit5;\r
122    TP_n[5] = TakeProfit6;\r
123    SL_n[0] = StopLoss1;\r
124    SL_n[1] = StopLoss2;\r
125    SL_n[2] = StopLoss3;\r
126    SL_n[3] = StopLoss4;\r
127    SL_n[4] = StopLoss5;\r
128    SL_n[5] = StopLoss6;\r
129    LastLoss_n[0] = 0;\r
130    LastLoss_n[1] = LastLoss2;\r
131    LastLoss_n[2] = LastLoss3;\r
132    LastLoss_n[3] = LastLoss4;\r
133    LastLoss_n[4] = LastLoss5;\r
134    LastLoss_n[5] = LastLoss6;\r
135    \r
136    ArrayInitialize(TradeOn_n, 0);\r
137    TradeOn_n[0] = 1;\r
138    if(UseTrade2) TradeOn_n[1] = 1;\r
139    if(UseTrade3) TradeOn_n[2] = 1;\r
140    if(UseTrade4) TradeOn_n[3] = 1;\r
141    if(UseTrade5) TradeOn_n[4] = 1;\r
142    if(UseTrade6) TradeOn_n[5] = 1;\r
143    ArrayInitialize(BuySell_n, 0);\r
144    if(BuySell2) BuySell_n[1] = 1;\r
145    if(BuySell3) BuySell_n[2] = 1;\r
146    if(BuySell4) BuySell_n[3] = 1;\r
147    if(BuySell5) BuySell_n[4] = 1;\r
148    if(BuySell6) BuySell_n[5] = 1;\r
149    \r
150    \r
151   \r
152    return(0);\r
153   }\r
154   \r
155 //+------------------------------------------------------------------+\r
156 //| expert deinitialization function                                 |\r
157 //+------------------------------------------------------------------+\r
158 int deinit()\r
159   {\r
160    // Clear the un-used Global Variables\r
161    GlobalVariablesDeleteAll(AdvisorName);\r
163    return(0);\r
164   }\r
165   \r
166 //+------------------------------------------------------------------+\r
167 //| expert start function                                            |\r
168 //+------------------------------------------------------------------+\r
169 int start()\r
170   {\r
171    // BreakEven && TrailStop && StealthMode\r
172    if(scanTrades(TRADETRADE)>0) {\r
173       if(UseBreakEven) breakEven();\r
174       if(UseTrailStop) trailStop();\r
175       if(StealthMode) stealthMode();\r
176    }\r
177    \r
178    // buy pattern = bear candle  bear candle bull candle bear candle\r
179    // sell pattern = bear candle  bull candle bear candle bear candle\r
180    int cond_buy[3], cond_sell[3];\r
181  \r
182    cond_buy[0] = CANDLE_BULL;\r
183    cond_buy[1] = CANDLE_BULL;\r
184    cond_buy[2] = CANDLE_BEAR;\r
186    cond_sell[0] = CANDLE_BEAR;\r
187    cond_sell[1] = CANDLE_BEAR;\r
188    cond_sell[2] = CANDLE_BULL;\r
189  \r
190    \r
191    bool cond_buy_fit[3], cond_sell_fit[3];\r
192    ArrayInitialize(cond_buy_fit, false);\r
193    ArrayInitialize(cond_sell_fit, false);\r
194    \r
195    int i, j, candle[3];\r
196    int candle_limit = ArraySize(candle);\r
197    ArrayInitialize(candle, CANDLE_NONE);\r
198    for(i=1,j=0; i<20 && j<candle_limit; i++) {\r
199       if(Close[i]-Open[i]>0) {\r
200          candle[j] = CANDLE_BULL;\r
201          j++;\r
202       }\r
203       else if(Close[i]-Open[i]<0) {\r
204          candle[j] = CANDLE_BEAR;\r
205          j++;\r
206       }\r
207       else if(Close[i]-Open[i]==0) {\r
208          candle[j] = 2;\r
209          j++;\r
210         // continue;\r
211       }\r
212    }\r
213    \r
214    if(time_check<Time[0]) {\r
215       time_check = Time[0];\r
216       Print("Candle:",DoubleToStr(candle[0],0),"-",DoubleToStr(candle[1],0),"-",DoubleToStr(candle[2],0),"-",DoubleToStr(candle[3],0));\r
217       Print("Buy:",DoubleToStr(cond_buy[0],0),"-",DoubleToStr(cond_buy[1],0),"-",DoubleToStr(cond_buy[2],0),"-",DoubleToStr(cond_buy[3],0));\r
218       Print("Sell:",DoubleToStr(cond_sell[0],0),"-",DoubleToStr(cond_sell[1],0),"-",DoubleToStr(cond_sell[2],0),"-",DoubleToStr(cond_sell[3],0));  \r
219    }\r
220    \r
221    for(i=0; i<candle_limit; i++) {\r
222       if(candle[i]==cond_buy[i]) {\r
223          cond_buy_fit[i] = true;\r
224       }\r
225       if(candle[i]==cond_sell[i]) {\r
226          cond_sell_fit[i] = true;\r
227       }\r
228    }\r
229    \r
230    bool cond_buy_ready=true, cond_sell_ready=true;\r
231    for(i=0; i<candle_limit; i++) {\r
232       if(cond_buy_fit[i]==false) {\r
233          cond_buy_ready=false;\r
234       }\r
235       if(cond_sell_fit[i]==false) {\r
236          cond_sell_ready=false;\r
237       }\r
238    }\r
239    \r
240    // Trade Time Filter\r
241    if(!TradeTimeFilter || (TradeTimeFilter && tradeTime())) {\r
242       Lots = Lots_n[0];\r
243       TakeProfit = TP_n[0];\r
244       StopLoss = SL_n[0];\r
245       if(!tradedInBar() && scanTrades(TRADETRADE)==0 && cond_buy_ready) {\r
246          ArrayInitialize(tickets, 0);\r
247          num_trades = 0;\r
248          tradeBuy();\r
249       \r
250       }\r
251       if(!tradedInBar() && scanTrades(TRADETRADE)==0 && cond_sell_ready) {\r
252          ArrayInitialize(tickets, 0);\r
253          num_trades = 0;\r
254          tradeSell();\r
255       }\r
256       \r
257       // Open More\r
258       if(num_trades>0) {\r
259          OrderSelect(tickets[num_trades-1], SELECT_BY_TICKET);\r
260          if(TradeOn_n[num_trades]>0 && profit2Pips(OrderSymbol(),OrderProfit(),OrderLots())>=LastLoss_n[num_trades] && OrderProfit()>0) {\r
261             Lots = Lots_n[num_trades];\r
262             TakeProfit = TP_n[num_trades];\r
263             StopLoss = SL_n[num_trades];\r
264             if(BuySell_n[num_trades]>0) {\r
265                tradeBuy();\r
266             }\r
267             else {\r
268                tradeSell();\r
269             }\r
270          }\r
271       }\r
272    }\r
273    \r
274   // Close\r
275    if(num_trades>0 && scanTrades(TRADETRADE)>0) {\r
276       OrderSelect(tickets[num_trades -1], SELECT_BY_TICKET);\r
277       if(OrderStopLoss()>0 && OrderCloseTime()>0) {\r
278          while(scanTrades(TRADETRADE)>0) {\r
279             closeTrades();\r
280          }\r
281       }\r
282       \r
283       if(ordersProfit()>ProfitTarget) {\r
284          while(scanTrades(TRADETRADE)>0) {\r
285             closeTrades();\r
286          }\r
287       }\r
288    }\r
290    return(0);\r
291   }\r
292   \r
293 //+------------------------------------------------------------------+\r
294 //| Total Profit of sepcific type of orders @http://kolier.li        |\r
295 //+------------------------------------------------------------------+\r
296 double ordersProfit(int order_dir=TRADEALL)\r
297   {\r
298    double profit = 0;\r
299    for(int i=0; i<OrdersTotal(); i++) {\r
300       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
301       if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) {\r
302          switch(order_dir) {\r
303             case TRADEALL:\r
304                profit += OrderProfit();\r
305                break;\r
306             case TRADEBUY:\r
307                if(OrderType()==OP_BUY) {\r
308                   profit += OrderProfit();\r
309                }\r
310                break;\r
311             case TRADESELL:\r
312                if(OrderType()==OP_SELL) {\r
313                   profit += OrderProfit();\r
314                }\r
315                break;\r
316          }// switch\r
317       }\r
318    }\r
319   \r
320    return(profit);\r
321   }\r
324 //+------------------------------------------------------------------+\r
325 //| Trade Time Filter @http://kolier.li                              |\r
326 //|   @see http://kolier.li/example/script-function-trade-time-filter|\r
327 //+------------------------------------------------------------------+\r
328 bool tradeTime()\r
329   {\r
330    if(TradeTimeFilter) {\r
331       datetime time_now, time_begin, time_end, time_end_today;\r
332       time_now = TimeCurrent();\r
333       time_begin = StrToTime(TradeBegin);\r
334       if(!EndInTomorrow) {\r
335          time_end = StrToTime(TradeEnd);\r
336       }\r
337       else if(EndInTomorrow) {\r
338          time_end = StrToTime(TradeEnd) + 86400;\r
339          time_end_today = StrToTime(TradeEnd);\r
340       }\r
341       if(!EndInTomorrow && (time_now<time_begin || time_now>time_end)) {\r
342          return(false);\r
343       }\r
344       else if(EndInTomorrow && time_now>time_end_today && time_now<time_begin) {\r
345          return(false);\r
346       }\r
347    }\r
348    return(true);  \r
349   }\r
350   \r
351 //+------------------------------------------------------------------+\r
352 //| Trade Buy @http://kolier.li @v1.0                                |\r
353 //| @import                                                          |\r
354 //|   bool ECNBroker                                                 |\r
355 //+------------------------------------------------------------------+\r
356 void tradeBuy()\r
357   {\r
358    double price_now, price_profit, price_stop, lots;\r
359    double take_profit = pips2Points(TakeProfit)*Point;\r
360    double stop_loss = pips2Points(StopLoss)*Point;\r
361    int ticket;\r
362    price_now = Ask;\r
363    if(TakeProfit > 0) {\r
364       price_profit = price_now + take_profit;\r
365    }\r
366    else {\r
367       price_profit = 0;\r
368    }\r
369    if(StopLoss > 0) {\r
370       price_stop = price_now - stop_loss;\r
371    }\r
372    else {\r
373       price_stop = 0;\r
374    }\r
375    lots = Lots;\r
376    /*\r
377    if(MoneyManagement) {\r
378       lots = mmLots(stop_loss);\r
379    }\r
380    else {\r
381       lots = Lots;\r
382    }\r
383    */\r
384    \r
385    if(!ECNBroker && !StealthMode) {\r
386       ticket = OrderSend(Symbol(), OP_BUY, lots, price_now, Slippage, price_stop, price_profit, NULL, Magic, 0, Lime);\r
387    }\r
388    else {\r
389       ticket = OrderSend(Symbol(), OP_BUY, lots, price_now, Slippage, 0, 0, NULL, Magic, 0, Lime);\r
390    }\r
391    \r
392    if(ticket < 0) {\r
393       //tradeBuy();\r
394       Print(AdvisorName, "- tradeBuy() error #", GetLastError());\r
395       Print("Price Buy: ", price_now, " TP: ", price_profit, " SL: ", price_stop, " Lots: ", lots);\r
396    }\r
397    else {\r
398       OrderSelect(ticket, SELECT_BY_TICKET);\r
399       if(ECNBroker) { \r
400          OrderModify(OrderTicket(), OrderOpenPrice(), price_stop, price_profit, 0, CLR_NONE);\r
401       }\r
402       tickets[num_trades] = ticket;\r
403       num_trades++;\r
404    }\r
405   }\r
406   \r
407 //+------------------------------------------------------------------+\r
408 //| Trade Sell @http://kolier.li @v1.0                               |\r
409 //| @import                                                          |\r
410 //|   bool ECNBroker                                                 |\r
411 //+------------------------------------------------------------------+\r
412 void tradeSell()\r
413   {\r
414    double price_now, price_profit, price_stop, lots;\r
415    double take_profit = pips2Points(TakeProfit)*Point;\r
416    double stop_loss = pips2Points(StopLoss)*Point;\r
417    int ticket;\r
418    price_now = Bid;\r
419    if(TakeProfit > 0) {\r
420       price_profit = price_now - take_profit;\r
421    }\r
422    else {\r
423       price_profit = 0;\r
424    }\r
425    if(StopLoss > 0) {\r
426       price_stop = price_now + stop_loss;\r
427    }\r
428    else {\r
429       price_stop = 0;\r
430    }\r
431    lots = Lots;\r
432    /*\r
433    if(MoneyManagement) {\r
434       lots = mmLots(stop_loss);\r
435    }\r
436    else {\r
437       lots = Lots;\r
438    }\r
439    */\r
441    if(!ECNBroker && !StealthMode) {\r
442       ticket = OrderSend(Symbol(), OP_SELL, lots, price_now, Slippage, price_stop, price_profit, NULL, Magic, 0, Red);\r
443    }\r
444    else {\r
445       ticket = OrderSend(Symbol(), OP_SELL, lots, price_now, Slippage, 0, 0, NULL, Magic, 0, Red);\r
446    }\r
447    \r
448    if(ticket < 0) {\r
449       //tradeBuy();\r
450       Print(AdvisorName, "- tradeSell() error #", GetLastError());\r
451       Print("Price Sell: ", price_now, " TP: ", price_profit, " SL: ", price_stop, " Lots: ", lots);\r
452    }\r
453    else {\r
454       OrderSelect(ticket, SELECT_BY_TICKET);\r
455       if(ECNBroker) {  \r
456          OrderModify(OrderTicket(), OrderOpenPrice(), price_stop, price_profit, 0, CLR_NONE);\r
457       }\r
458       tickets[num_trades] = ticket;\r
459       num_trades++;\r
460    }\r
461   }\r
462   \r
463 //+------------------------------------------------------------------+\r
464 //| Close All Trades @http://kolier.li                               |\r
465 //+------------------------------------------------------------------+\r
466 void closeTrades()\r
467   {\r
468    for(int i=0; i<OrdersTotal(); i++) {\r
469       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
470       if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_BUY) {\r
471          OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(),MODE_BID), Slippage, White);\r
472       }\r
473       else if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_SELL) {\r
474          OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(),MODE_ASK), Slippage, White);\r
475       }\r
476    }\r
477   }\r
478   \r
479 //+------------------------------------------------------------------+\r
480 //| TP and SL stealthly, hide from the trade server                  |\r
481 //| Place at the front part of start()                               |\r
482 //+------------------------------------------------------------------+\r
483 void stealthMode()\r
484   {\r
485    double takeprofit_stealth = pips2Points(TakeProfit)*Point;\r
486    double stoploss_stealth = pips2Points(StopLoss)*Point;\r
487       \r
488    for(int i=0; i<OrdersTotal(); i++) {\r
489       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
490       if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) {\r
491          if(OrderType()==OP_BUY\r
492             && ( (MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice()>=takeprofit_stealth && takeprofit_stealth>0)\r
493                || (OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_BID)>=stoploss_stealth && stoploss_stealth>0) )) {\r
494             OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, White);\r
495          }\r
496          else if(OrderType()==OP_SELL\r
497             && ( (OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK)>=takeprofit_stealth && takeprofit_stealth>0)\r
498                || (MarketInfo(OrderSymbol(),MODE_ASK)-OrderOpenPrice()>=stoploss_stealth && stoploss_stealth>0) )) {\r
499             OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, White);\r
500          }\r
501       }\r
502    }\r
503   }\r
504   \r
505 //+------------------------------------------------------------------+\r
506 //| pips2Points() @http://kolier.li                                  |\r
507 //+------------------------------------------------------------------+\r
508 double pips2Points(double pips)\r
509   {\r
510    double points;\r
511    if(Close[0]<10) {\r
512       points = pips*MathPow(10,Digits-4);\r
513    }\r
514    else if(Close[0]>10) {\r
515       points = pips*MathPow(10,Digits-2);  \r
516    }\r
517    \r
518    return(points);\r
519   }\r
521 //+------------------------------------------------------------------+\r
522 //| trailStop Target Points                                          |\r
523 //| Scan Trades @http://kolier.li @v1.0                              |\r
524 //| @params                                                          |\r
525 //|   string order_type TRADEALL|TRADETRADE|TRADEPEND                |\r
526 //|   string order_dir TRADEALL|TRADEBUY|TRADESELL                   |\r
527 //| @return                                                          |\r
528 //|   int orders_number                                              |\r
529 //+------------------------------------------------------------------+\r
530 int scanTrades(int order_type=TRADEALL, int order_dir=TRADEALL)\r
531   {\r
532    int orders_total = OrdersTotal();\r
533    int orders_number = 0;\r
534    for(int i=0; i<orders_total; i++)\r
535    {\r
536       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
537       if(OrderMagicNumber() == Magic && OrderSymbol() == Symbol()) {\r
538          switch(order_type) {\r
539             case TRADEALL:\r
540                orders_number++;\r
541                break;\r
542             case TRADETRADE:\r
543                if(OrderType()<=OP_SELL) {\r
544                   orders_number = _scanTradesDir(order_dir, orders_number);\r
545                }\r
546                break;\r
547             case TRADEPEND:\r
548                if(OrderType()>OP_SELL) {\r
549                   orders_number = _scanTradesDir(order_dir, orders_number);\r
550                }\r
551                break;\r
552          }// switch\r
553       }\r
554    }\r
555    return(orders_number);   \r
556   }\r
557   \r
558 int _scanTradesDir(int order_dir, int orders_number)\r
559   {\r
560       switch(order_dir) {\r
561          case TRADEALL:\r
562             orders_number++;\r
563             break;\r
564          case TRADEBUY:\r
565             if(OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP) {\r
566                orders_number++;\r
567             }\r
568             break;\r
569          case TRADESELL:\r
570             if(OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP) {\r
571                orders_number++;\r
572             }\r
573             break;\r
574       }// switch\r
575       return(orders_number);\r
576   }\r
577   \r
578 //+------------------------------------------------------------------+\r
579 //| Break Even @http://kolier.li                                     |\r
580 //+------------------------------------------------------------------+\r
581 void breakEven()\r
582   {\r
583    int orders_total = OrdersTotal();\r
584    int i, ticket;\r
585    double break_even_points = pips2Points(BreakEvenPips);\r
586    double break_even_with_profit = pips2Points(BreakEvenWithProfit);\r
587    double stoploss_buy, stoploss_sell;\r
588    string gv_name;\r
589    double break_even_able;\r
590    \r
591    for(i=0; i<orders_total; i++) {\r
592       break_even_able = -1;\r
593       if(!BreakEvenWithProfit) {\r
594          stoploss_buy = OrderOpenPrice();\r
595          stoploss_sell = OrderOpenPrice();\r
596       }\r
597       else {\r
598          stoploss_buy = OrderOpenPrice() + break_even_with_profit*Point;\r
599          stoploss_sell = OrderOpenPrice() - break_even_with_profit*Point;\r
600       }\r
601       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
602       if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderProfit()>0) {\r
603          if(BE_StealthMode) {\r
604             break_even_able = GlobalVariableGet(AdvisorName+"_be_able_"+OrderTicket());\r
605             if(OrderType()==OP_BUY && break_even_able>0 && Bid<=stoploss_buy) {\r
606                OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, White);\r
607             }\r
608             else if(OrderType()==OP_SELL && break_even_able>0 && Ask>=stoploss_sell) {\r
609                OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, White);\r
610             }\r
611          }\r
612       \r
613          if(OrderType()==OP_BUY && (OrderStopLoss()<stoploss_buy || OrderStopLoss()==0)\r
614             && Bid-OrderOpenPrice()>=break_even_points*Point) {\r
615             if(!BE_StealthMode) {\r
616                OrderModify(OrderTicket(), OrderOpenPrice(), stoploss_buy, OrderTakeProfit(), 0, Green);\r
617             }\r
618             else {\r
619                GlobalVariableSet(AdvisorName+"_be_able_"+OrderTicket(), 1);\r
620             }\r
621          }\r
622          else if(OrderType()==OP_SELL && (OrderStopLoss()>stoploss_sell || OrderStopLoss()==0)\r
623             && OrderOpenPrice()-Ask>=break_even_points*Point) {\r
624             if(!BE_StealthMode) {\r
625                OrderModify(OrderTicket(), OrderOpenPrice(), stoploss_sell, OrderTakeProfit(), 0, Magenta);\r
626             }\r
627             else {\r
628                GlobalVariableSet(AdvisorName+"_be_able_"+OrderTicket(), 1);\r
629             }\r
630          }\r
631       }\r
632    }\r
633    \r
634    // Clear the un-used Global Variables\r
635    for(i=0; i<GlobalVariablesTotal(); i++) {\r
636       gv_name = GlobalVariableName(i);\r
637       if(StringSubstr(gv_name, 0, 8+StringLen(AdvisorName))==AdvisorName+"_be_able") {\r
638          ticket = StrToInteger(StringSubstr(gv_name, 8+StringLen(AdvisorName)));\r
639          OrderSelect(ticket, SELECT_BY_TICKET);\r
640          if(OrderCloseTime()>0) {\r
641             GlobalVariableDel(gv_name);\r
642          }\r
643       }\r
644    }\r
645   }\r
647 //+------------------------------------------------------------------+\r
648 //| Trail Stop @http://kolier.li                                     |\r
649 //+------------------------------------------------------------------+\r
650 void trailStop()\r
651   {\r
652    int ticket;\r
653    string gv_name;\r
654    double trail_stop_points = pips2Points(TrailStopPips)*Point;\r
655    double ts_chunk = pips2Points(TS_Chunk)*Point;\r
656    double stoploss_order;\r
657    \r
658    for(int i=0; i<OrdersTotal(); i++) {\r
659       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
660       if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) {\r
661          if(!TS_StealthMode) {\r
662             stoploss_order = OrderStopLoss();\r
663          }\r
664          else {\r
665             stoploss_order = GlobalVariableGet("ts_stoploss_"+OrderTicket());\r
666             \r
667             if(stoploss_order>0) {\r
668                if(OrderType()==OP_BUY && Bid<=stoploss_order) {\r
669                   OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, White);\r
670                   GlobalVariableDel(AdvisorName+"_ts_stoploss_"+OrderTicket());\r
671                   continue;\r
672                }\r
673                else if(OrderType()==OP_SELL && Ask>=stoploss_order) {\r
674                   OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, White);\r
675                   GlobalVariableDel(AdvisorName+"_ts_stoploss_"+OrderTicket());\r
676                   continue;\r
677                }\r
678             }\r
679          }\r
681          if(OrderType()==OP_BUY\r
682             && ((Bid-trail_stop_points>stoploss_order && stoploss_order>0) || stoploss_order==0)\r
683             && (!TrailAfterEven || (TrailAfterEven && Bid-trail_stop_points>=OrderOpenPrice()))\r
684             && (!TS_MovingInChunk || (TS_MovingInChunk && ((Bid-stoploss_order>trail_stop_points+ts_chunk && stoploss_order>0) || stoploss_order==0)))) {\r
685             if(!TS_StealthMode) {\r
686                OrderModify(OrderTicket(), OrderOpenPrice(), Bid-trail_stop_points, OrderTakeProfit(), 0, Blue);\r
687             }\r
688             else {\r
689                GlobalVariableSet(AdvisorName+"_ts_stoploss_"+OrderTicket(), Bid-trail_stop_points);\r
690             }\r
691          }\r
692          else if(OrderType()==OP_SELL\r
693             && ((Ask+trail_stop_points<stoploss_order && stoploss_order>0) || stoploss_order==0)\r
694             && (!TrailAfterEven || (TrailAfterEven && Ask+trail_stop_points<=OrderOpenPrice()))\r
695             && (!TS_MovingInChunk || (TS_MovingInChunk && ((stoploss_order-Ask>trail_stop_points+ts_chunk && stoploss_order>0) || stoploss_order==0)))) {\r
696             if(!TS_StealthMode) {\r
697                OrderModify(OrderTicket(), OrderOpenPrice(), Ask+trail_stop_points, OrderTakeProfit(), 0, Orange);\r
698             }\r
699             else {\r
700                GlobalVariableSet(AdvisorName+"_ts_stoploss_"+OrderTicket(), Ask+trail_stop_points);\r
701             }\r
702          }\r
703       }\r
704    }\r
705    \r
706    // Clear the un-used Global Variables\r
707    for(i=0; i<GlobalVariablesTotal(); i++) {\r
708       gv_name = GlobalVariableName(i);\r
709       if(StringSubstr(gv_name, 0, 12+StringLen(AdvisorName))==AdvisorName+"_ts_stoploss") {\r
710          ticket = StrToInteger(StringSubstr(gv_name, 12+StringLen(AdvisorName)));\r
711          OrderSelect(ticket, SELECT_BY_TICKET);\r
712          if(OrderCloseTime()>0) {\r
713             GlobalVariableDel(gv_name);\r
714          }\r
715       }\r
716    }\r
717   }\r
718   \r
719 //+------------------------------------------------------------------+\r
720 //| Whether traded in that bar, default to current bar               |\r
721 //| @http://kolier.li                                                |\r
722 //+------------------------------------------------------------------+\r
723 bool tradedInBar(int shift=0)\r
724   {\r
725    datetime time_begin = Time[shift];\r
726    datetime time_end = time_begin + Period()*60;\r
727    int i;\r
728    for(i=0; i<OrdersTotal(); i++)\r
729    {\r
730       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
731       if(OrderMagicNumber()==Magic && OrderSymbol()==Symbol()\r
732         && OrderOpenTime()>=time_begin && OrderOpenPrice()<=time_end) {\r
733          return(true);\r
734       }\r
735    }\r
736    for(i=0; i<OrdersHistoryTotal(); i++)\r
737    {\r
738       OrderSelect(i, SELECT_BY_POS, MODE_HISTORY);\r
739       if(OrderMagicNumber()==Magic && OrderSymbol()==Symbol()\r
740         && OrderOpenTime()>=time_begin && OrderOpenPrice()<=time_end) {\r
741          return(true);\r
742       }\r
743    }\r
744    \r
745    return(false);\r
746   }\r
747   \r
748 //+------------------------------------------------------------------+\r
749 //| Convert the orders profit into pips @http://kolier.li            |\r
750 //+------------------------------------------------------------------+\r
751 double profit2Pips(string symbol, double profit, double lots)\r
752   {\r
753    double tick_value = MarketInfo(symbol, MODE_TICKVALUE);\r
754    double points = profit/(lots*tick_value);\r
755    double pips = points2Pips(points);\r
757    return(pips);\r
758   }\r
759   \r
760 //+------------------------------------------------------------------+\r
761 //| points2Pips() @http://kolier.li                                  |\r
762 //+------------------------------------------------------------------+\r
763 double points2Pips(double points)\r
764   {\r
765    double pips;\r
766    if(Close[0]<10) {\r
767       pips = points/MathPow(10,Digits-4);\r
768    }\r
769    else if(Close[0]>10) {\r
770       pips = points/MathPow(10,Digits-2);\r
771    }\r
772    \r
773    return(pips);\r
774   }